﻿package org.baicaix.demo.zip {
	import riaidea.utils.zip.ZipArchive;
	import riaidea.utils.zip.ZipEvent;
	import riaidea.utils.zip.ZipFile;

	import flash.events.Event;

	//	import deng.fzip.FZip;
//	import deng.fzip.FZipFile;


	/**
	 * 替换屏蔽字
	 * @author dengyang
	 */
	public class KeyWordPlace {

		private static var me : KeyWordPlace;
		private var isInit : Boolean = false;
		private var _zip : ZipArchive;
		private var wordList : Array;
		private var regexList : Array;
		private static var spliteOpration : String = "=";

		public function KeyWordPlace() {
			trace("init...");
			if(me != null) {
				throw new Error("请使用 getInstance方法获取实例。");
			}
		}

		public function init(url : String) : void {
//			var textLoader : URLLoader = new URLLoader();
//			textLoader.addEventListener(Event.COMPLETE, textLoaded);
//			textLoader.load(new URLRequest(url));
			_zip = new ZipArchive();
			_zip.addEventListener(ZipEvent.ZIP_INIT, onComplete);
			_zip.load(url);
//			zip = new FZip();
//			zip.addEventListener(Event.COMPLETE, onComplete);
//			zip.load(new URLRequest(url));
		}

		private function onComplete(evt : Event=null) : void {
			trace("========KeyWordPlace load completed...");
			trace('zip: ' + (this._zip));
			trace('file: ' + (this._zip.getFileByName("keywords.txt")));
			var file : ZipFile = this._zip.getFileByName("keywords.txt");
			wordList = file.data.readMultiByte(file.data.length, "UTF-8").split("\n");
			
			regexList = [];
			for each (var word : String in wordList) {
				var index : int = word.indexOf(spliteOpration);
				var key : String = word.substr(0, index == -1 ? 0 : index);
				regexList.push(new RegExp(key, "g"));
			}
			this.isInit = true;
		}

		public static function getInstance() : KeyWordPlace {
			if(me == null) {
				me = new KeyWordPlace();
			}
			return me;
		}

		
//		private function textLoaded(e : Event) : void {
//			trace("========KeyWordPlace load completed...");
//			wordList = e.target.data.split("\n");
//			regexList = [];
//			for each (var word : String in wordList) {
//				var index : int = word.indexOf(spliteOpration);
//				var key : String = word.substr(0, index == -1 ? 0 : index);
//				regexList.push(new RegExp(key, "g"));
//			}
//			this.isInit = true;
//		}

		public function replace(befor : String) : String {
//			if(!isInit) throw new Error("关键字替换尚未初始化完毕...");
			trace("========KeyWordPlace " + regexList.length);
			for each (var i : RegExp in regexList) {
				befor = befor.replace(i, "***");
			}
			return befor;
		}
	}
}
